package com.guandi.geekbrowser.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.guandi.geekbrowser.Utils.DESHelper;
import com.guandi.geekbrowser.Utils.EasyUtil;
import com.guandi.geekbrowser.primary.entity.Details;
import com.guandi.geekbrowser.primary.entity.Ipool;
import com.guandi.geekbrowser.primary.entity.Message;
import com.guandi.geekbrowser.primary.entity.Tab;
import com.guandi.geekbrowser.primary.service.DetailsService;
import com.guandi.geekbrowser.primary.service.IpoolService;
import com.guandi.geekbrowser.primary.service.TabService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Controller
public class MainViewController {

    @Autowired
    private DetailsService detailsService;
    @Autowired
    private TabService tabService;
    @Autowired
    private IpoolService ipoolService;

    private DESHelper desHelper = new DESHelper("zDsGrVKQ");

    @RequestMapping(value = "/getTabs", method = RequestMethod.POST)
    @ResponseBody
    public List<Tab> getTabs(@RequestBody JSONObject jsonObject) {
        String userId = jsonObject.getString("userId");
        String country = jsonObject.getString("country");
        Integer type = jsonObject.getInteger("type");
        if (!EasyUtil.isEmpty(userId) && !EasyUtil.isEmpty(country)&&type!=null) {
            userId = desHelper.decrypt(userId);
            List<Tab> list = tabService.findByUserIdAndCountryAndType(userId, country,type);
            return list;
        } else {
            return null;
        }
    }

    @RequestMapping(value = "/getTabByName", method = RequestMethod.POST)
    @ResponseBody
    public Tab getTabByName(@RequestBody JSONObject jsonObject) {
        String name = jsonObject.getString("name");
        String userId = jsonObject.getString("userId");
        String country = jsonObject.getString("country");
        if (!EasyUtil.isEmpty(name) && !EasyUtil.isEmpty(userId) && !EasyUtil.isEmpty(country)) {
            userId = desHelper.decrypt(userId);
            Tab tab = tabService.findByUserIdAndNameAndCountry(userId, name, country);
            return tab;
        }
        return null;
    }

    @RequestMapping(value = "/getTestDetails", method = RequestMethod.POST)
    @ResponseBody
    public String getTestDetails(@RequestBody JSONObject jsonObject){
        String userId = jsonObject.getString("userId");
        Integer type = jsonObject.getInteger("type");
        String country = jsonObject.getString("country");
        if(!EasyUtil.isEmpty(userId)&&!EasyUtil.isEmpty(country)&&type!=null){
            userId = desHelper.decrypt(userId);
            List<Details> list = detailsService.findByUserIdAndCountryAndType(userId, country, type);
            return JSONObject.toJSONString(list);
        }
        return "";
    }

    @RequestMapping(value = "/getDetails", method = RequestMethod.POST)
    @ResponseBody
    public Page<Details> getDetails(@RequestBody JSONObject jsonObject) {
        String userId = jsonObject.getString("userId");
        String tabName = jsonObject.getString("tabName");
        String country = jsonObject.getString("country");
        String searchWord = jsonObject.getString("searchWord");
        Integer pageNumber = jsonObject.getInteger("pageNumber");
        Integer pageSize = jsonObject.getInteger("pageSize");
        Integer type = jsonObject.getInteger("type");
        if (!EasyUtil.isEmpty(userId) && !EasyUtil.isEmpty(country)&&type!=null) {
            userId = desHelper.decrypt(userId);
//            List<Details> details = detailsService.findByTabNameAndUserId(tabName, userId);
            Page<Details> detailsPage = detailsService.findAllPageByTabNameAndUserIdAndCountry(tabName, userId, pageNumber, pageSize, country,searchWord,type);
            return detailsPage;
        } else {
            return null;
        }
    }

    @RequestMapping(value = "/addDetails", method = RequestMethod.POST)
    @ResponseBody
    public String addDetails(@RequestBody JSONObject object) {
        String userId = object.getString("userId");
        String tabName = object.getString("tabName");
        String country = object.getString("country");
        Integer type = object.getInteger("type");
        Message message = new Message();
        if (!EasyUtil.isEmpty(userId) && !EasyUtil.isEmpty(tabName)&&type!=null) {
            userId = desHelper.decrypt(userId);
            Object detailsObj = object.get("details");
            String jsonString = JSONObject.toJSONString(detailsObj);
            JSONObject jsonObject = JSONObject.parseObject(jsonString);
            if (jsonObject != null && jsonObject.size() > 0) {
                String account = jsonObject.getString("account");
                String password = jsonObject.getString("password");
                String mailPassword = jsonObject.getString("mailPassword");
                String notes = jsonObject.getString("notes");
                if (!EasyUtil.isEmpty(account) && !EasyUtil.isEmpty(mailPassword) && !EasyUtil.isEmpty(country)) {
                    Details detailTemp = new Details();
                    detailTemp.setUserId(userId.trim());
                    detailTemp.setTabName(tabName.trim());
                    detailTemp.setRegisterDate(new Date());
                    detailTemp.setAccount(account.trim());
                    detailTemp.setMailPassword(mailPassword.trim());
                    detailTemp.setNotes(notes);
                    detailTemp.setCountry(country);
                    detailTemp.setPassword(password);
                    detailTemp.setType(type);
                    detailsService.saveDetails(detailTemp);
                    message.setSuccess(true);
                    message.setMessage("账号信息添加成功!");
                } else {
                    message.setSuccess(false);
                    message.setMessage("账号或邮箱密码不能为空!");
                }
            } else {
                message.setSuccess(false);
                message.setMessage("参数异常!");
            }
        } else {
            message.setSuccess(false);
            message.setMessage("分组信息不存在!");
        }
        return JSONObject.toJSONString(message);
    }

    @RequestMapping(value = "/addTab", method = RequestMethod.POST)
    @ResponseBody
    public String addTab(@RequestBody JSONObject object) {
        String userId = object.getString("userId");
        Integer type = object.getInteger("type");
        Message message = new Message();
        if (!EasyUtil.isEmpty(userId)&&type!=null) {
            userId = desHelper.decrypt(userId);
            Object tab = object.get("tab");
            String s = JSONObject.toJSONString(tab);
            JSONObject jsonObject = JSONObject.parseObject(s);
            if (jsonObject != null && jsonObject.size() > 0) {
                String name = jsonObject.getString("name");
                String password = jsonObject.getString("password");
                String country = object.getString("country");
                if (!EasyUtil.isEmpty(name)) {
                    if (!EasyUtil.isEmpty(country)) {
                        name = name.trim();
                        Tab tabUse = tabService.findByUserIdAndNameAndCountry(userId, name, country);
                        if (tabUse == null) {
                            Tab tabTemp = new Tab();
                            tabTemp.setUserId(userId);
                            tabTemp.setDel(false);
                            tabTemp.setName(name);
                            tabTemp.setType(type);
                            tabTemp.setCountry(country);
                            if (StringUtils.isEmpty(password) || "".equals(password.trim())) {
                                tabTemp.setPassword(null);
                            } else {
                                tabTemp.setPassword(password.trim());
                            }
                            tabService.saveTab(tabTemp);
                            message.setParams(tabTemp.getName());
                            message.setSuccess(true);
                            message.setMessage("添加成功!");
                        } else {
                            message.setSuccess(false);
                            message.setMessage("分组名称已存在!");
                        }
                    } else {
                        message.setSuccess(false);
                        message.setMessage("国家不能为空!");
                    }
                } else {
                    message.setSuccess(false);
                    message.setMessage("分组名称不能为空!");
                }
            } else {
                message.setSuccess(false);
                message.setMessage("参数错误!");
            }
        } else {
            message.setSuccess(false);
            message.setMessage("用户异常!");
        }
        return JSONObject.toJSONString(message);
    }

    @RequestMapping(value = "/updateTab", method = RequestMethod.POST)
    @ResponseBody
    public String updateTab(@RequestBody JSONObject object) {
        String userId = (String) object.get("userId");
        Object tab = object.get("curTab");
        JSONObject json = JSONObject.parseObject(JSONObject.toJSONString(tab));
        Message message = new Message();
        if (!EasyUtil.isEmpty(userId) && json.size() > 0) {
            userId = desHelper.decrypt(userId);
            Integer id = (Integer) json.get("id");
            String passwordNew = (String) json.get("password");
            String name = (String) json.get("name");
            if (!EasyUtil.isEmpty(name)) {
                name = name.trim();
                List<Tab> list = tabService.findByName(name);
                if (list == null) {
                    Optional<Tab> tabOldOpt = tabService.findById(id.longValue());
                    if (tabOldOpt.isPresent()) {
                        Tab tabOld = tabOldOpt.get();
                        if (StringUtils.isEmpty(passwordNew) || "".equals(passwordNew.trim())) {
                            tabOld.setPassword(null);
                        } else {
                            tabOld.setPassword(passwordNew);
                        }
                        List<Details> tempList = detailsService.findByTabNameAndUserId(tabOld.getName(), userId);
                        String finalName = name;
                        tempList.stream().forEach(f -> {
                            f.setTabName(finalName);
                            detailsService.saveDetails(f);
                        });
                        tabOld.setName(name);
                        tabService.saveTab(tabOld);
                        message.setSuccess(true);
                        message.setMessage("更新成功!");
                        message.setParams(tabOld.getName());
                    } else {
                        message.setSuccess(false);
                        message.setMessage("分组不存在!");
                    }
                } else {
                    message.setSuccess(false);
                    message.setMessage("分组名称已存在!");
                }
            } else {
                message.setSuccess(false);
                message.setMessage("分组名称不能为空!");
            }
        } else {
            message.setSuccess(false);
            message.setMessage("参数错误!");
        }
        return JSONObject.toJSONString(message);
    }

    @RequestMapping(value = "/delTab", method = RequestMethod.POST)
    @ResponseBody
    public String delTab(@RequestBody JSONObject object) {
        String userId = object.getString("userId");
        String tabName = object.getString("tabName");
        String country = object.getString("country");
        Message message = new Message();
        if (!EasyUtil.isEmpty(userId) && !EasyUtil.isEmpty(tabName) && !EasyUtil.isEmpty(country)) {
            userId = desHelper.decrypt(userId);
            Tab tab = tabService.findByUserIdAndNameAndCountry(userId, tabName, country);
            if (tab != null) {
                Integer integer = detailsService.deleteAllByTabNameAndUserIdAndCountry(tabName, userId, country);
                if (integer >= 0) {
                    tabService.deleteByUserIdAndNameAndCountry(userId, tabName, country);
                }
                message.setSuccess(true);
                message.setMessage("删除成功!");
            } else {
                message.setSuccess(false);
                message.setMessage("分组不存在!");
            }
        } else {
            message.setSuccess(false);
            message.setMessage("参数异常!");
        }
        return JSONObject.toJSONString(message);
    }

    @RequestMapping(value = "/updateDetails", method = RequestMethod.POST)
    @ResponseBody
    public String updateDetails(@RequestBody JSONObject object) {
        String userId = (String) object.get("userId");
        Object detail = object.get("detail");
        String jsonString = JSONObject.toJSONString(detail);
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        Message message = new Message();
        if (!EasyUtil.isEmpty(userId) && jsonObject.size() > 0) {
            String account = jsonObject.getString("account");
            String password = jsonObject.getString("password");
            String mailPassword = jsonObject.getString("mailPassword");
            String notes = jsonObject.getString("notes");
            Integer id = (Integer) jsonObject.get("id");
            userId = desHelper.decrypt(userId);
            Details details = detailsService.findByIdAndUserId(id.longValue(), userId);
            if (details != null) {
                if (!EasyUtil.isEmpty(account) && !EasyUtil.isEmpty(mailPassword)) {
                    details.setAccount(account);
                    details.setMailPassword(mailPassword);
                    details.setPassword(password);
                    if(!EasyUtil.isEmpty(notes)) {
                        details.setNotes(notes);
                    }
                    detailsService.saveDetails(details);
                    message.setMessage("修改成功!");
                    message.setSuccess(true);
                } else {
                    message.setMessage("账号或邮箱密码不能为空!");
                    message.setSuccess(false);
                }
            } else {
                message.setMessage("账号不存在!");
                message.setSuccess(false);
            }
        } else {
            message.setMessage("参数错误!");
            message.setSuccess(false);
        }
        return JSONObject.toJSONString(message);
    }

    @RequestMapping(value = "/inputFile", method = RequestMethod.POST)
    @ResponseBody
    public String inputFile(@RequestParam("file") MultipartFile file, @RequestParam("userId") String userId,
                            @RequestParam("curTabName") String curTabName, @RequestParam("country") String country) {
        Message message = new Message();
        if (!file.isEmpty()) {
            if (!EasyUtil.isEmpty(userId)&&!EasyUtil.isEmpty(curTabName)) {
                try {
                    userId = desHelper.decrypt(userId);
                    List<Details> detailsList = EasyUtil.readExcel(file, curTabName, userId, country);
                    if (detailsList != null & detailsList.size() > 0) {
                        detailsService.saveDetailList(detailsList);
                        message.setMessage("上传成功!");
                        message.setSuccess(true);
                    } else {
                        message.setMessage("文件中没有数据!");
                        message.setSuccess(false);
                    }
                } catch (FileNotFoundException e) {
//                e.printStackTrace();
                    message.setMessage("上传失败," + e.getMessage());
                    message.setSuccess(false);
                } catch (IOException e) {
//                e.printStackTrace();
                    message.setMessage("上传失败," + e.getMessage());
                    message.setSuccess(false);
                }
            } else {
                message.setMessage("必须登录才能上传文件!");
                message.setSuccess(false);
            }
        } else {
            message.setMessage("上传失败，因为文件是空的!");
            message.setSuccess(false);
        }
        return JSONObject.toJSONString(message);
    }

    @RequestMapping(value = "/exportFile", method = RequestMethod.GET)
    @ResponseBody
    public String exportFile(HttpServletResponse response, @PathParam("tabName") String tabName) {
        List<Details> detailsList = detailsService.findByTabName(tabName);
        EasyUtil.exportExcel(tabName, response, detailsList);
        return "export file";
    }

    @RequestMapping(value = "/delDetail", method = RequestMethod.POST)
    @ResponseBody
    public String delDetail(@RequestBody JSONObject jsonObject) {
        String userId = jsonObject.getString("userId");
        Long detailId = jsonObject.getLong("detailId");
        Message message = new Message();
        if (!EasyUtil.isEmpty(userId) && detailId != null) {
            userId = desHelper.decrypt(userId);
            detailsService.deleteByIdAndUserId(detailId, userId);
            message.setSuccess(true);
            message.setMessage("删除成功!");
        } else {
            message.setSuccess(false);
            message.setMessage("删除失败!");
        }
        return JSONObject.toJSONString(message);
    }

    @RequestMapping(value = "/delDetailList", method = RequestMethod.POST)
    @ResponseBody
    public String delDetailList(@RequestBody JSONObject jsonObject) {
        String userId = jsonObject.getString("userId");
        JSONArray details = jsonObject.getJSONArray("details");
        Message message = new Message();
        if (!EasyUtil.isEmpty(userId)) {
            if (details != null && details.size() > 0) {
                List<Details> detailsList = details.toJavaList(Details.class);
                detailsService.deleteAll(detailsList);
                message.setSuccess(true);
                message.setMessage("删除成功!");
            }
        } else {
            message.setSuccess(false);
            message.setMessage("删除失败!");
        }


        return JSONObject.toJSONString(message);
    }

    @RequestMapping(value = "/changeNotes", method = RequestMethod.POST)
    @ResponseBody
    public String changeNotes(@RequestBody JSONObject jsonObject) {
        String userId = (String) jsonObject.get("userId");
        Message message = new Message();
        if (!EasyUtil.isEmpty(userId)) {
            userId = desHelper.decrypt(userId);
            Integer detailIdInt = (Integer) jsonObject.get("detailId");
            Long detailId = detailIdInt.longValue();
            String notes = (String) jsonObject.get("notes");
            Details details = detailsService.findByIdAndUserId(detailId, userId);
            if (details != null) {
                detailsService.updateOne(notes, detailId, userId);
                message.setSuccess(true);
                message.setMessage("修改成功!");
            } else {
                message.setSuccess(false);
                message.setMessage("账号不存在!");
            }
        } else {
            message.setSuccess(false);
            message.setMessage("用户异常!");
        }
        return JSON.toJSONString(message);
    }

    @RequestMapping(value = "/bindIpInfo", method = RequestMethod.POST)
    @ResponseBody
    public String bindIpInfo(@RequestBody JSONObject jsonObject) {
        String userId = jsonObject.getString("userId");
        String ipInfo = jsonObject.getString("ipInfo");
        String country = jsonObject.getString("country");
        String type = jsonObject.getString("type");
        long detailId = jsonObject.getLongValue("detailId");
        Message message = new Message();
        if (!EasyUtil.isEmpty(userId)) {
            if (!EasyUtil.isEmpty(type)) {
                userId = desHelper.decrypt(userId);
                Details details = detailsService.findByIdAndUserIdAndCountry(detailId, userId, country);
                if ("bind".equals(type) && details != null) {
                    details.setIpoolInfo(ipInfo);
                    changeIpBind(ipInfo, userId, country, 1);
                    detailsService.saveDetails(details);
                    message.setSuccess(true);
                    message.setMessage("IP信息绑定成功!");
                } else if ("unbind".equals(type) && details != null) {
                    details.setIpoolInfo(null);
                    changeIpBind(ipInfo, userId, country, 0);
                    detailsService.saveDetails(details);
                    message.setSuccess(true);
                    message.setMessage("解绑成功!");
                } else {
                    message.setSuccess(false);
                    message.setMessage("账号信息不存在!");
                }
            } else {
                message.setSuccess(false);
                message.setMessage("ip信息不能为空!");
            }
        } else {
            message.setSuccess(false);
            message.setMessage("用户异常!");
        }
        return JSONObject.toJSONString(message);
    }

    public void changeIpBind(String ipoolInfo, String userId, String country, Integer bind) {
        if (!EasyUtil.isEmpty(ipoolInfo)) {
            String address = "";
            String port = "";
            if (ipoolInfo.contains("|")) {
                int i = ipoolInfo.indexOf("|");
                String substring = ipoolInfo.substring(0, i);
                String[] ipPortSplit = substring.split(":");
                address = ipPortSplit[0];
                port = ipPortSplit[1];
            } else {
                String[] split = ipoolInfo.split(":");
                address = split[0];
                port = split[1];
            }
            Ipool ipool = ipoolService.findByAddressAndPortAndUserIdAndCountry(address, port, userId, country);
            if (ipool != null) {
                ipool.setBind(bind);
            }
            ipoolService.saveIpool(ipool);
        }
    }

    @RequestMapping(value = "/getFreeIp", method = RequestMethod.POST)
    @ResponseBody
    public String getFreeIp(@RequestBody JSONObject jsonObject) {
        String country = jsonObject.getString("country");
        List<Ipool> ipoolList = ipoolService.findByCountryAndType(country, 3);
        return null;
    }
}
